﻿Public Class ISCPacketHandler

    Public handler As ISCHandler

    Public Sub New(ByVal handler As ISCHandler)
        Me.handler = handler
    End Sub

    Public Sub handlePacket(ByVal buf() As Byte, ByVal index As Integer, ByVal len As Integer)
        Dim header As Integer = buf(index)
        Select Case header
            Case &H1
                addCluster(buf, index + 4)
                Exit Select
            Case &H2
                updateCluster(buf, index + 4)
                Exit Select
            Case Else
                log.log(LogType.MSG_ISC)
                log.log(LogType.MSG_RECV)
                For i As Integer = 0 To len - 1 Step i + 1
                    Console.Write("{0:x2} ", buf(i + index))
                Next
                Console.WriteLine()
                Exit Select
        End Select
    End Sub

    Public Sub addCluster(ByVal buf() As Byte, ByVal index As Integer)
        Dim cluster As New Cluster
        Dim offset As Integer = index

        cluster.name = ISCPacketCreator.getString(buf, offset)
        cluster.ip = ISCPacketCreator.getString(buf, offset)
        Dim channels As IList = New Collections.ArrayList
        Dim numChannels = ISCPacketCreator.getInt(buf, offset)
        Dim channelName = String.Empty
        For i As Integer = 1 To numChannels Step i + 1
            channelName = ISCPacketCreator.getString(buf, offset)
            channels.Add(channelName)
            channelName = String.Empty
        Next
        cluster.channels = channels
        If (ISC.clusters.Equals(Nothing) = False) Then
            ISC.clusters.Add(cluster)
            log.log(LogType.MSG_INFO, "Cluster added - " & cluster.name)
            handler.cluster = cluster
        Else
            handler.workSocket.Close()
        End If
    End Sub

    Public Sub updateCluster(ByVal buf() As Byte, ByVal index As Integer)
        Dim offset = index
        Dim name = ISCPacketCreator.getString(buf, offset)
        Dim cluster As New Cluster
        For Each obj As Object In ISC.clusters
            cluster = obj
            If cluster.name = name Then
                ISC.clusters.Remove(cluster)
                Exit For
            End If
        Next

        cluster = New Cluster
        cluster.name = name
        cluster.ip = ISCPacketCreator.getString(buf, offset)
        Dim channels As IList = New Collections.ArrayList
        Dim numChannels = ISCPacketCreator.getInt(buf, offset)
        Dim channelName = String.Empty
        For i As Integer = 1 To numChannels Step i + 1
            channelName = ISCPacketCreator.getString(buf, offset)
            channels.Add(channelName)
            channelName = String.Empty
        Next
        cluster.channels = channels
        ISC.clusters.Add(cluster)
    End Sub

End Class